const Mock = require('mockjs')

const OrgUnits = []
OrgUnits.push({
  id: 1,
  type: 2,
  name: '雷盎科技',
  createTime: Mock.Random.datetime(),
  status: 0,
  address: {
    addr: '广东省广州市番禺区洛浦街道',
    detailAddress: '东乡村一街',
    addressCode: {
      province: '440000',
      city: '440100',
      area: '440113',
      town: '440113013'
    },
    lng: 113.315451,
    lat: 23.041157
  }
})
for (let i = 2; i < 6; ++i) {
  OrgUnits.push(Mock.mock({
    id: i,
    type: 1,
    name: Mock.Random.cname() + '的店',
    createTime: Mock.Random.datetime(),
    status: 0,
    hideCloudMovie: i % 2,
    parentId: 1,
    parentName: '雷盎科技'
  }))
}

function add(orgUnit, parentId) {
  const ou = JSON.parse(JSON.stringify(orgUnit))
  ou.id = OrgUnits[OrgUnits.length - 1].id + 1
  ou.createTime = new Date()
  ou.parentId = parentId
  ou.status = 0
  const p = find(parentId)
  if (p) {
    ou.parentName = p.name
  }
  OrgUnits.push(ou)
}

function list(page, limit, type, name) {
  limit = Math.max(1, Math.min(parseInt(limit), 50))
  page = Math.max(parseInt(page), 1)
  type = type ? parseInt(type) : null
  let mocks = OrgUnits.filter(item => {
    if (type && type !== item.type) return false
    return !(name && (!item.name || item.name.indexOf(name) === -1))
  })
  const total = mocks.length
  mocks = mocks.filter((u, index) => index < limit * page && index >= limit * (page - 1))
  return { success: true, data: { total: total, records: mocks }}
}

function find(id) {
  id = id ? parseInt(id) : null
  for (let i = 0; i < OrgUnits.length; ++i) {
    if (OrgUnits[i].id === id) {
      return OrgUnits[i]
    }
  }
  return null
}

module.exports = { list, add, find }
